package br.progweb.webapp.util.customeditor;

import br.progweb.webapp.model.Grupo;
import br.progweb.webapp.service.GrupoManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.beans.PropertyEditorSupport;

/**
 * Created with IntelliJ IDEA.
 * User: luiza
 * Date: 09/09/12
 * Time: 18:36
 * To change this template use File | Settings | File Templates.
 */
@Component
public class GroupCustomEditor extends PropertyEditorSupport {
// ------------------------------ FIELDS ------------------------------

    @Autowired
    private GrupoManager grupoManager;

// ------------------------ INTERFACE METHODS ------------------------


// --------------------- Interface PropertyEditor ---------------------

    @Override
    public String getAsText() {
        Grupo value = (Grupo) getValue();
        return (value != null ? value.getDescricao() : "");
    }

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        Grupo grupo =  null;
        try {
            grupo = grupoManager.get(Long.parseLong(text));
        } catch (RuntimeException ex){
            setValue(new Grupo());
        }

        setValue(grupo);
    }
}
